package com.example.bingobox.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bingobox.R;
import com.example.bingobox.model.TodoBox;
import com.example.bingobox.model.Task;
import com.example.bingobox.model.Label;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
import android.widget.ImageButton;
import java.util.stream.Collectors;
import android.widget.Toast;
import android.widget.Button;
import androidx.annotation.NonNull;

public class TodoBoxAdapter extends RecyclerView.Adapter<TodoBoxAdapter.ViewHolder> {
    private Context context;
    private List<TodoBox> todoBoxes;
    private Map<String, Task> taskMap;
    private OnTodoBoxActionListener listener;
    private Runnable onDataChanged;
    private Set<String> expandedBoxIds = new HashSet<>();  // 跟踪展开状态的任务盒ID
    private List<Label> labels;

    public interface OnTodoBoxActionListener {
        void onExpandClick(TodoBox todoBox);
        void onEditClick(TodoBox todoBox);
        void onDeleteClick(TodoBox todoBox);
        void onDrawTask(TodoBox todoBox, Task task);
        void onEditTask(TodoBox todoBox, Task task);
        void onDeleteTask(TodoBox todoBox, Task task);
    }

    public TodoBoxAdapter(Context context, List<TodoBox> todoBoxes, Map<String, Task> taskMap, 
            List<Label> labels, Runnable onDataChanged, OnTodoBoxActionListener listener) {
        this.context = context;
        this.todoBoxes = new ArrayList<>(todoBoxes);
        this.taskMap = taskMap;
        this.labels = labels;
        this.onDataChanged = onDataChanged;
        this.listener = listener;
    }

    private boolean isTaskAvailable(Task task, Calendar now) {
        // 如果任务没有时间标签，则始终可用
        if (task.getTimeLabels() == null || task.getTimeLabels().isEmpty()) {
            return true;
        }

        // 获取当前时间
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int minute = now.get(Calendar.MINUTE);
        
        // 获取当前是星期几
        int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);
        String day;
        
        // 转换为小写的星期几
        switch (dayOfWeek) {
            case Calendar.MONDAY: day = "monday"; break;
            case Calendar.TUESDAY: day = "tuesday"; break;
            case Calendar.WEDNESDAY: day = "wednesday"; break;
            case Calendar.THURSDAY: day = "thursday"; break;
            case Calendar.FRIDAY: day = "friday"; break;
            case Calendar.SATURDAY: day = "saturday"; break;
            case Calendar.SUNDAY: day = "sunday"; break;
            default: day = "monday";
        }

        // 从 labels 中获取当前星期对应的日期类型
        String dayType = null;
        for (Label label : labels) {
            if (label.getStandard().equals("week") && label.getCoupleData() != null) {
                dayType = label.getCoupleData().getCouple().get(day);
                break;
            }
        }

        if (dayType == null) return false;

        // 当前时间（以分钟为单位）
        int currentTime = hour * 60 + minute;

        // 遍历所有时间标签
        for (Task.TimeLabel timeLabel : task.getTimeLabels()) {
            // 检查日期类型是否匹配
            if (timeLabel.getDayType().equals(dayType)) {
                // 如果是全天标签，则匹配成功
                if (timeLabel.isAllDay()) {
                    return true;
                }
                
                // 计算开始和结束时间（分钟）
                int startTime = timeLabel.getStartHour() * 60 + timeLabel.getStartMinute();
                int endTime = timeLabel.getEndHour() * 60 + timeLabel.getEndMinute();
                
                // 处理跨天的情况
                if (endTime < startTime) {  // 如果结束时间小于开始时间，说明跨天
                    if (currentTime >= startTime || currentTime <= endTime) {
                        return true;
                    }
                } else {
                    // 不跨天的情况，直接判断时间范围
                    if (currentTime >= startTime && currentTime <= endTime) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public Task drawRandomTask(TodoBox todoBox) {
        if (todoBox.getListData() == null || todoBox.getListData().getList() == null) {
            return null;
        }

        List<TodoBox.TaskRef> availableTasks = new ArrayList<>();
        Calendar now = Calendar.getInstance();

        // 筛选符合时间标签的任务
        for (TodoBox.TaskRef ref : todoBox.getListData().getList()) {
            Task task = taskMap.get(ref.getTaskId());
            if (task != null && !task.isCompleted() && isTaskAvailable(task, now)) {
                availableTasks.add(ref);
            }
        }

        if (availableTasks.isEmpty()) {
            return null;
        }

        // 随机选择一个任务
        int index = new Random().nextInt(availableTasks.size());
        String taskId = availableTasks.get(index).getTaskId();
        return taskMap.get(taskId);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView nameText;
        TextView descText;
        View btnEdit;
        View btnDelete;
        View btnDraw;
        ImageButton expandButton;
        View detailsContainer;

        ViewHolder(View view) {
            super(view);
            nameText = view.findViewById(R.id.text_todobox_name);
            descText = view.findViewById(R.id.text_todobox_description);
            btnEdit = view.findViewById(R.id.btn_edit);
            btnDelete = view.findViewById(R.id.btn_delete);
            btnDraw = view.findViewById(R.id.btn_draw);
            expandButton = view.findViewById(R.id.btn_expand);
            detailsContainer = view.findViewById(R.id.layout_details_container);
        }
    }

    private String formatDate(long timestamp) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timestamp);
        return String.format("%d年%d月%d日", 
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH) + 1,
            cal.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_todobox, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TodoBox todoBox = todoBoxes.get(position);
        
        // 设置任务盒名称和描述
        holder.nameText.setText(todoBox.getName());
        holder.descText.setText(todoBox.getDescription());
        
        // 设置展开按钮的状态和点击事件
        holder.expandButton.setRotation(todoBox.isExpanded() ? 180 : 0);
        holder.expandButton.setOnClickListener(v -> {
            if (listener != null) {
                listener.onExpandClick(todoBox);
            }
        });

        // 根据展开状态显示或隐藏详细信息
        holder.detailsContainer.setVisibility(todoBox.isExpanded() ? View.VISIBLE : View.GONE);
        
        // 如果是展开状态，设置任务列表
        if (todoBox.isExpanded()) {
            RecyclerView taskList = holder.detailsContainer.findViewById(R.id.list_tasks);
            if (taskList != null && todoBox.getListData() != null && todoBox.getListData().getList() != null) {
                taskList.setLayoutManager(new LinearLayoutManager(context));
                List<Task> tasks = todoBox.getListData().getList().stream()
                    .map(ref -> taskMap.get(ref.getTaskId()))
                    .filter(task -> task != null)
                    .collect(Collectors.toList());
                TaskListAdapter taskAdapter = new TaskListAdapter(tasks, todoBox, listener);
                taskList.setAdapter(taskAdapter);
            }
        }

        // 设置按钮点击事件
        holder.btnEdit.setOnClickListener(v -> {
            if (listener != null) {
                listener.onEditClick(todoBox);
            }
        });
        
        holder.btnDelete.setOnClickListener(v -> {
            if (listener != null) {
                listener.onDeleteClick(todoBox);
            }
        });
        
        holder.btnDraw.setOnClickListener(v -> {
            if (listener != null) {
                Task task = drawRandomTask(todoBox);
                if (task != null) {
                    listener.onDrawTask(todoBox, task);
                } else {
                    // 如果没有可用任务，显示提示
                    Toast.makeText(context, "当前没有可抽取的任务", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return todoBoxes.size();
    }

    public void updateTodoBoxes(List<TodoBox> newTodoBoxes) {
        // 只保留可见的任务盒
        List<TodoBox> visibleTodoBoxes = new ArrayList<>();
        for (TodoBox todoBox : newTodoBoxes) {
            if (todoBox.isVisible()) {
                visibleTodoBoxes.add(todoBox);
            }
        }
        
        this.todoBoxes.clear();
        this.todoBoxes.addAll(visibleTodoBoxes);
        notifyDataSetChanged();
        if (onDataChanged != null) {
            onDataChanged.run();
        }
    }

    // 修改任务列表适配器
    private class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.ViewHolder> {
        private final List<Task> tasks;
        private final TodoBox todoBox;
        private final OnTodoBoxActionListener listener;

        TaskListAdapter(List<Task> tasks, TodoBox todoBox, OnTodoBoxActionListener listener) {
            this.tasks = tasks;
            this.todoBox = todoBox;
            this.listener = listener;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_task_in_todobox, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Task task = tasks.get(position);
            holder.nameText.setText(task.getName());
            holder.deadlineText.setText(formatDate(task.getDeadline()));
            
            holder.btnEdit.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onEditTask(todoBox, task);
                }
            });
            
            holder.btnDelete.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onDeleteTask(todoBox, task);
                }
            });
        }

        @Override
        public int getItemCount() {
            return tasks.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView nameText;
            TextView deadlineText;
            View btnEdit;
            View btnDelete;

            ViewHolder(View view) {
                super(view);
                nameText = view.findViewById(R.id.text_task_name);
                deadlineText = view.findViewById(R.id.text_task_deadline);
                btnEdit = view.findViewById(R.id.btn_edit);
                btnDelete = view.findViewById(R.id.btn_delete);
            }
        }
    }
} 